package main

import "fmt"

// 不使用递归但使用闭包改写第 6.6 节中的斐波那契数列程序。
// func fibonacci(n int) (res int) {
// 	if n <= 1 {
// 		res = 1
// 	} else {
// 		res = fibonacci(n-1) + fibonacci(n-2)
// 	}
// 	return
// }

func fibonacci(n int) (res uint64) {
	list := make([]uint64, n)
	list[0] = 1
	list[1] = 1
	f := func(m int) {
		list[m] = list[m-1] + list[m-2]
	}
	if n < 1 {
		n = 1
	}
	for i := 2; i < n; i++ {
		f(i)
	}
	res = list[n-1]
	return
}

func fib() func() uint64 {
	var a, b uint64
	a, b = 1, 1
	// very nice code
	return func() uint64 {
		a, b = b, a+b
		return b
	}

}

func fibo(n int) (res uint64) {
	f := fib()
	for i := 2; i < n-1; i++ {
		f()
	}
	res = f()
	return
}

func main() {
	fmt.Println("66 fibonacci number is: ", fibonacci(66))
	fmt.Println("88 fibonacci number is: ", fibo(88))
}
